<?php

namespace App\Services\ES;

use Laravel\Scout\Builder;
use Laravel\Scout\Searchable;

trait SubSearchable
{
    use Searchable;

    /**
     * It's been active when import data to index.
     *
     * @param $chunk
     */
    public static function makeAllSearchable($chunk = null)
    {
        $tableName = static::tableName() . $chunk;
        $model = new static();
        $self = $model->setTable($tableName);

        $softDelete = static::usesSoftDelete() && config('scout.soft_delete', false);

        $self->newQuery()
            ->when(true, function ($query) use ($self) {
                $self->makeAllSearchableUsing($query);
            })
            ->when($softDelete, function ($query) {
                $query->withTrashed();
            })
            ->orderBy($self->getKeyName())
            ->searchable();
    }

    /**
     * Perform a search against the model's indexed data.
     *
     * @param  string  $query
     * @param  \Closure  $callback
     * @return \Laravel\Scout\Builder
     */
    public static function search($query = '', $callback = null)
    {
        return app(Builder::class, [
            'model' => new static,
            'query' => $query,
            'callback' => $callback,
            'softDelete'=> static::usesSoftDelete() && config('scout.soft_delete', false),
        ])->tap(function ($query) {
            $result = collect();
            foreach ($query->keys() as $id) {
                $result = $result->merge(static::getInstance($id)->get());
            }
            return $result;
        });
    }

}
